﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HyEduOnline.Entities;
using HyEduOnline.Server.Teacher;
using WebSite.Models;
using HyEduOnline.Server.Admin;
using HyEduOnline.Data;
using System.Data;
using HyEduOnline.Models;
using HyEduOnline.Services;
using HyEduOnline.Server.Student;

namespace HyEduOnline.Controllers
{
    [UserAuthorizeTea]
    public class TeacherController : Controller
    {


        private TeachersDAO TeachersDAO = new TeachersDAO();


        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Home()
        {
            //当前教师所授课程
            string teaCode = frontCurrentTea.GetNo();//取当前登录的教师工号

            VwDeanCourseDAO vwCourse = new VwDeanCourseDAO();
            int count = 0;
            //从视图中获取当前教师所教授的课程信息
            List<VwDeanCourse> CourseList = vwCourse.GetByPageVW("S_TeacherCode='" + teaCode + "'", 0, int.MaxValue, "Id", "DESC", out count).ToList();
            ViewBag.Course = CourseList;
            return View();
        }

        /// <summary>
        /// 教师的导航
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            ViewBag.TeaName = frontCurrentTea.GetUserName();
            if (Session["Image"] != null)
            {
                ViewBag.ImageUrl = Session["Image"].ToString();
            }
            return View();
        }

        //个人信息
        public ActionResult Personal()
        {
            string teaCode = frontCurrentTea.GetNo();
            TbTeachers list = TeachersDAO.GetByPage("S_TeaNo = '" + teaCode + "'", 0, int.MaxValue).ToList()[0];

            return View(list);
        }

        //学生端教师信息展示页面
        public ActionResult TeacherMassage(int TeaID)
        {
            TbTeachers list = TeachersDAO.GetByID(TeaID);
            return View(list);
        }

        //课程介绍
        public ActionResult CourseIntro()
        {
            string teaCode = frontCurrentTea.GetNo();//取当前登录的教师工号

            VwDeanCourseDAO vwCourse = new VwDeanCourseDAO();
            int count = 0;
            //从视图中获取当前教师所教授的课程信息
            List<VwDeanCourse> CourseList = vwCourse.GetByPageVW("S_TeacherCode='" + teaCode + "'", 0, int.MaxValue, "Id", "DESC", out count).ToList();
            ViewBag.CourseList = CourseList;

            return View();
        }


        //教学大纲编辑页面
        public ActionResult TeachingOutline(int id)
        {
            //课程Id
            ViewBag.Id = id;
            return View();
        }

        //课程详情显示页面
        public ActionResult OutlineShow(int CourseId)
        {
            //ViewBag.CourseName = CourseName;//课程名
            ViewBag.CourseID = CourseId;
            TbDeanCourse course = new DeanCourseDAO().GetByID(CourseId);
            ViewBag.Course = course;
            frontCurrentTea.SetCurrentCourseID(CourseId);
            string imgUrl = "";
            if (!string.IsNullOrEmpty(course.SImgUrl))
            {
                imgUrl = ViewBag.Course.SImgUrl.Replace("/middle/", "/large/");
            }
            ViewBag.Course.SImgUrl = imgUrl;
            //教学大纲所有内容
            ViewBag.teaCatalog = new TeaCatalogDAO().GetByPage("I_DeanCourseID =" + CourseId, 0, int.MaxValue);
            return View();
        }

        //密码修改
        public ActionResult ChangePassword()
        {
            return View();
        }

        //教师个人资源
        public ActionResult TeaResource()
        {
            return View();
        }


        //教学资源
        public ActionResult PublicResource(int CourseID)
        {
            ViewBag.CourseID = CourseID;
            ViewBag.CourseName = new DeanCourseDAO().GetByID(CourseID).SCourseName;
            return View();
        }

        //试卷列表
        public ActionResult PaperList(int courseId)
        {
            Session["TempCourseID"] = courseId;
            ViewBag.CourseID = courseId;
            string TeaCode = "2014";//frontCurrentTea.GetNo();
            //获得当前课程的所有试卷
            ViewBag.paperList = new TestLibPaperDAO().GetByPage(
                "S_TeaCode='" + TeaCode + "' and I_CourseID=" + courseId, 0, int.MaxValue);
            return View();
        }


        //评卷
        public ActionResult MarkPaper(int paperId)
        {
            //取得当前学期id和教师编号
            int TermId = 1;
            int CourseID = (int)Session["TempCourseID"];
            string TeaCode = "2014";//frontCurrentTea.GetNo();

            //获得参加考试的所有班级
            DataSet classDSTemp = DataRepository.Provider.TbDeanStuSelCourseProvider.selClass(TeaCode, CourseID, TermId);
            DataTable classDTTemp = classDSTemp.Tables[0];
            List<TbDeanStuSelCourse> classList = new List<TbDeanStuSelCourse>();
            //循环表的每一行
            foreach (DataRow item in classDTTemp.Rows)
            {
                TbDeanStuSelCourse stuClass = new TbDeanStuSelCourse();
                stuClass.IClassId = int.Parse(item[0].ToString());
                stuClass.SClassCode = item[1].ToString();
                stuClass.SClassName = item[2].ToString();
                classList.Add(stuClass);
            }
            ViewBag.classList = classList;//班级列表
            ViewBag.CourseID = CourseID;
            ViewBag.paperId = paperId;
            return View();
        }


        //学生答卷
        public ActionResult StuAnswerDetail(string stuCode, int paperId, int score)
        {
            TestStuAnswerDAO testStuAnswerDAO = new TestStuAnswerDAO();
            //当前答卷信息
            ViewBag.paper = new TestScoresDAO().GetByPage("S_StuCode='" + stuCode + "' and I_PaperID=" + paperId, 0, int.MaxValue)[0];

            ViewBag.score = score;

            ViewBag.CourseId = Session["TempCourseID"];
            List<TestPaperExt> tempStrategyContent = new List<TestPaperExt>();   //定义大题的对象集(策略和其附属的小题)

            string WhereClause = "I_PaperID=" + paperId;  //在策略表中查询试卷的策略
            TList<TbTestPaperStrategy> tempStrategy = new TestPaperStrategyDAO().GetByPage(WhereClause, 0, int.MaxValue);


            if (tempStrategy.Count > 0)   //存在该试卷的策略，同时返回该试卷的策略个数
            {
                foreach (var item in tempStrategy)
                {
                    List<QuestExt> TestLiblist = new List<QuestExt>();   //定义题库的对象集（小题和可能存在的选项）//解决问题所在 9.19
                    TestPaperExt tem = new TestPaperExt();
                    tem.StrategyItem = item;//获取当前的策略
                    tem.stuGetScore = testStuAnswerDAO.GetByPage(
                        "S_StuCode='" + stuCode + "' and I_StrateID=" + item.Id, 0, int.MaxValue)[0].IScore.ToString();
                    string whereClause1 = "I_StrategyID=" + item.Id;
                    TList<TbTestLibPaperDetail> tempDetailList = new TestLibPaperDetailDAO().GetByPage(whereClause1, 0, int.MaxValue); //获取每一个大题中的小题题id
                    if (tempDetailList.Count > 0)
                    {
                        foreach (var item1 in tempDetailList)
                        {
                            int DetailId = (int)item1.Id;
                            QuestExt TtempList = new QuestExt();//获取试题集
                            string libID = item1.ILibId.ToString();
                            int LibID = int.Parse(libID);
                            TbTestLib tempLib = new TestLibDAO().GetByID(LibID); //获取小题的详细信息
                            if (tempLib != null)
                            {

                                TtempList.LibItem = tempLib;   //把每一个试题放到list中
                                var problemtype = tempLib.IProblemType;  //获取策略的大题类型

                                string WhereClause1 = "I_LibID=" + tempLib.Id;
                                TList<TbTestLibOption> optionLists = new TestLibOptionDAO().GetByPage(WhereClause1, 0, int.MaxValue);//获取该题对应的选项
                                if (optionLists.Count > 0)  //该题存在选项
                                {
                                    TtempList.OptionList = optionLists;
                                }

                                //根据题型,筛选学生答案
                                TList<TbTestStuAnswerOptions> stuSelTemp = new TestStuAnswerOptionsDAO().GetByPage(
                                    "S_StuCode='" + stuCode + "' and I_LibID=" + LibID, 0, int.MaxValue);
                                string stuAnswer = "";
                                foreach (var item2 in stuSelTemp)
                                {
                                    string str = new TestLibOptionDAO().GetByID((int)item2.IOptionId).SOptionName;
                                    stuAnswer = stuAnswer + "," + str;
                                }
                                TtempList.StuAnswer = stuAnswer;

                                //该题是否正确
                                TList<TbTestStuAnswerDetail> tempList = new TestStuAnswerDetailDAO().GetByPage(
                                    "S_StuCode='" + stuCode + "' and I_PaperDetailID=" + DetailId, 0, int.MaxValue);
                                if (tempList.Count() > 0)
                                    TtempList.isOk = (int)tempList[0].IIsTrue;
                            }
                            TestLiblist.Add(TtempList);//获取选项集及试题

                        }
                        tem.LibItemList = TestLiblist;//获取当前策略的附属题集 

                    }

                    tempStrategyContent.Add(tem);  //该策略 
                }


            }
            //返回策略的详细信息，返回策略的个数
            ViewBag.TestPaperDetail = tempStrategyContent;

            return View();
        }


        //试卷分析
        public ActionResult AnalysePaper(int paperId)
        {
            int count = 0;
            string digitalStr = "";
            int[] digital = new int[12];//前十个数字代表每个分数段人数，第十一个代表考试人数，第十二个代表挂科人数
            TbTestLibPaper paper = new TestLibPaperDAO().GetByID(paperId);
            ViewBag.paper = paper;
            TList<TbTestScores> scoreList = new TestScoresDAO().GetByPage("I_PaperID=" + paperId, 0, int.MaxValue, "ID", "DESC", out count);
            digital[10] = count;
            foreach (var item in scoreList)
            {
                int score = (int)item.IScore;
                if (score < 10) { digital[0]++; digital[11]++; }
                if (score >= 10 && score < 20) { digital[1]++; digital[11]++; }
                if (score >= 20 && score < 30) { digital[2]++; digital[11]++; }
                if (score >= 30 && score < 40) { digital[3]++; digital[11]++; }
                if (score >= 40 && score < 50) { digital[4]++; digital[11]++; }
                if (score >= 50 && score < 60) { digital[5]++; digital[11]++; }
                if (score >= 60 && score < 70) { digital[6]++; }
                if (score >= 70 && score < 80) { digital[7]++; }
                if (score >= 80 && score < 90) { digital[8]++; }
                if (score >= 90 && score <= 100) { digital[9]++; }
            }
            foreach (var item in digital)
            {
                digitalStr = digitalStr + "," + item;
            }
            digitalStr = digitalStr.Substring(1, digitalStr.Length - 1);
            ViewBag.digitalStr = digitalStr;
            //获得参加考试的所有班级
            //取得当前学期id和教师编号
            int TermId = 1;
            int CourseID = (int)Session["TempCourseID"];
            string TeaCode = "2014";//frontCurrentTea.GetNo();
            DataSet classDSTemp = DataRepository.Provider.TbDeanStuSelCourseProvider.selClass(TeaCode, CourseID, TermId);
            DataTable classDTTemp = classDSTemp.Tables[0];
            List<TbDeanStuSelCourse> classList = new List<TbDeanStuSelCourse>();
            //循环表的每一行
            foreach (DataRow item in classDTTemp.Rows)
            {
                TbDeanStuSelCourse stuClass = new TbDeanStuSelCourse();
                stuClass.IClassId = int.Parse(item[0].ToString());
                stuClass.SClassCode = item[1].ToString();
                stuClass.SClassName = item[2].ToString();
                classList.Add(stuClass);
            }
            ViewBag.classList = classList;//班级列表
            return View();
        }


        /// <summary>
        /// 教师菜单栏
        /// </summary>
        /// <returns></returns>
        public ActionResult Menu()
        {
            ViewBag.MenuTree = Session["SysMenus"];
            return View();
        }

        /// <summary>
        /// 布置的习题集
        /// </summary>
        /// <param name="courseId"></param>
        /// <returns></returns>
        public ActionResult Practice(int courseId)
        {
            ViewBag.CourseID = courseId;
            ViewBag.teaId = frontCurrentTea.GetUserID();
            ViewBag.catalog = new TeaCatalogDAO().GetByPage("I_DeanCourseID = " + courseId, 0, int.MaxValue);
            string whereClause = "I_ParentID=0  and I_DeanCourseID=" + courseId;
            ViewBag.teaCatalog = new TeaCatalogDAO().GetByPage("I_DeanCourseID =" + courseId, 0, int.MaxValue);
            return View();
        }

        /// <summary>
        /// 学生完成的习题集
        /// </summary>
        /// <param name="PraId"></param>
        /// <param name="courseId"></param>
        /// <returns></returns>
        public ActionResult StuPractice(int PraId, int courseId)
        {
            ViewBag.PraId = PraId;
            ViewBag.CourseID = courseId;
            return View();
        }


        //学生查看练习集页面
        public ActionResult PracticeResult(int praId, string stuCode)
        {
            int oneLib = 0; //小题分数
            TestLibDAO libDAO = new TestLibDAO();
            TestLibOptionDAO optionDAO = new TestLibOptionDAO();
            int[] tempStrategy = { 1, 2, 3 };
            List<int> score = new List<int>();
            //当前习题信息
            TbStuPractice practice = new StuPracticeDAO().GetByPage(
                "I_PracticeID=" + praId + " and S_StuCode='" + stuCode + "'", 0, int.MaxValue)[0];
            ViewBag.pra = practice;
            int courseId = (int)practice.ICourseId;
            if (practice == null)
                return Json(0);
            //取出当前学生的信息
            ViewBag.stu = new StudentsDAO().findBySNo(stuCode)[0];

            //取出练习的章节
            TbStuPracticeList pra = new StuPracticeListDAO().GetByID(praId);
            string[] catalog = pra.SCatalog.Split(new char[] { ',' });
            //取出练习的章节 END

            List<TestPaperExt> tempStrategyContent = new List<TestPaperExt>();   //定义大题的对象集(策略和其附属的小题)

            if (tempStrategy.Length > 0)   //存在该试卷的策略，同时返回该试卷的策略个数
            {
                foreach (var item in tempStrategy)
                {
                    int stuScore = 0;//学生得分
                    int libCount = 0;//小题数量
                    
                    List<QuestExt> TestLiblist = new List<QuestExt>();   //定义题库的对象集（小题和可能存在的选项）//解决问题所在 9.19
                    TestPaperExt tem = new TestPaperExt();
                    TbTestPaperStrategy StrategyItem = new TbTestPaperStrategy();
                    StrategyItem.Id = item;
                    tem.StrategyItem = StrategyItem;//获取当前的策略
                    TList<TbTestLib> tempDetailList = new TList<TbTestLib>();
                    foreach (var cata in catalog)
                    {
                        TList<TbTestLib> tempLibLi = libDAO.GetByPage(
                            "I_CousreID=" + courseId
                            + " and I_StuOpen = 1 and I_ProblemType=" + item
                            + " and I_TeaCatalog = " + cata, 0, int.MaxValue);
                        tempDetailList.AddRange(tempLibLi);
                    }


                    foreach (var item1 in tempDetailList)
                    {

                        QuestExt TtempList = new QuestExt();//获取试题集

                        TbTestLib tempLib = item1; //获取小题的详细信息
                        if (tempLib != null)
                        {
                            TtempList.LibItem = tempLib;   //把每一个试题放到list中
                            var problemtype = tempLib.IProblemType;  //获取策略的大题类型

                            string WhereClause1 = "I_LibID=" + tempLib.Id;
                            TList<TbTestLibOption> optionLists = new TestLibOptionDAO().GetByPage(WhereClause1, 0, int.MaxValue);//获取该题对应的选项
                            if (optionLists.Count > 0)  //该题存在选项
                            {
                                TtempList.OptionList = optionLists;
                            }

                            //根据题型,筛选学生答案
                            TList<TbStuPracticeOptions> stuSelTemp = new StuPracticeOptionsDAO().GetByPage(
                                "S_StuCode='" + stuCode + "' and I_LibID=" + tempLib.Id + " and I_PracticeID=" + praId, 0, int.MaxValue);
                            string stuAnswer = "";
                            foreach (var item2 in stuSelTemp)
                            {
                                string str = new TestLibOptionDAO().GetByID((int)item2.IOptionId).SOptionName;
                                stuAnswer = stuAnswer + "," + str;
                            }

                            TtempList.StuAnswer = stuAnswer;

                            //该题是否正确
                            TList<TbStuPracticeDetail> tempList = new StuPracticeDetailDAO().GetByPage(
                                "S_StuCode='" + stuCode + "' and I_PraID=" + praId
                                + " and I_LibID=" + tempLib.Id, 0, int.MaxValue);
                            
                            if (tempList.Count() > 0)
                            {
                                int IScore = (int)tempList[0].IScore;
                                TtempList.isOk = (int)tempList[0].IIsTrue;
                                stuScore += IScore;
                                if (oneLib == 0)
                                {
                                    if (IScore != 0)
                                    {
                                        oneLib = (int)tempList[0].IScore;
                                    }
                                }
                            }
                            libCount++;
                        }
                        
                        TestLiblist.Add(TtempList);//获取选项集及试题

                    }
                    score.Add(libCount * oneLib);
                    tem.stuGetScore = stuScore.ToString();
                    tem.LibItemList = TestLiblist;//获取当前策略的附属题集 



                    tempStrategyContent.Add(tem);  //该策略 
                }


            }

            ViewBag.score = score;
            ViewBag.TestPaperDetail = tempStrategyContent;

            return View();
        }



        /// <summary>
        /// 预览练习题，点击“编辑”按钮时使用
        /// </summary>
        /// <param name="PracticeID"></param>
        /// <returns></returns>
        public ActionResult PracticePaperPreview(int PracticeID)
        {
            TestLibDAO libDAO = new TestLibDAO();
            TestLibOptionDAO optionDAO = new TestLibOptionDAO();
            int[] tempStrategy = { 1, 2, 3 };
            string stuCode = frontCurrentStu.GetNo();
            //当前习题信息
            TbStuPracticeList practice = new StuPracticeListDAO().GetByID(PracticeID);
            ViewBag.pra = practice;
            int courseId = (int)practice.ICourseId;
            TbDeanCourse tempDeanCourse = new DeanCourseDAO().GetByID(courseId);
            if (tempDeanCourse != null)
            {
                ViewBag.CourseName = tempDeanCourse.SCourseName;  //返回课程名称
            }
            if (practice == null)
                return Json(0);

            string[] catalog = practice.SCatalog.Split(new char[] { ',' });

            int TotalNum = 0;  //记录练习题的总的小题的个数

            List<TestPaperExt> tempStrategyContent = new List<TestPaperExt>();   //定义大题的对象集(策略和其附属的小题)

            if (tempStrategy.Length > 0)   //存在该试卷的策略，同时返回该试卷的策略个数
            {
                foreach (var item in tempStrategy)
                {
                    List<QuestExt> TestLiblist = new List<QuestExt>();   //定义题库的对象集（小题和可能存在的选项）//解决问题所在 9.19
                    TestPaperExt tem = new TestPaperExt();
                    TbTestPaperStrategy StrategyItem = new TbTestPaperStrategy();
                    int TestLibTota = 0;// 记录每一个策略的小题的数量
                    StrategyItem.Id = item;
                    tem.StrategyItem = StrategyItem;//获取当前的策略


                    TList<TbTestLib> tempDetailList = libDAO.GetByPage(
                    "I_CousreID=" + courseId
                    + " and I_StuOpen = 1 and I_ProblemType=" + item
                    + " and I_TeaCatalog = " + catalog[0], 0, int.MaxValue);

                    foreach (var item1 in tempDetailList)
                    {

                        TestLibTota++;  //循环统计
                        TotalNum++;//统计练习题的小题的总数
                        QuestExt TtempList = new QuestExt();//获取试题集

                        TbTestLib tempLib = item1; //获取小题的详细信息
                        if (tempLib != null)
                        {
                            TtempList.LibItem = tempLib;   //把每一个试题放到list中
                            var problemtype = tempLib.IProblemType;  //获取策略的大题类型

                            string WhereClause1 = "I_LibID=" + tempLib.Id;
                            TList<TbTestLibOption> optionLists = new TestLibOptionDAO().GetByPage(WhereClause1, 0, int.MaxValue);//获取该题对应的选项
                            if (optionLists.Count > 0)  //该题存在选项
                            {
                                TtempList.OptionList = optionLists;
                            }


                        }
                        TestLiblist.Add(TtempList);//获取选项集及试题

                    }
                    tem.StrategyItem.INum = TestLibTota;  //每一个策略下的小题的数量
                    tem.LibItemList = TestLiblist;//获取当前策略的附属题集 



                    tempStrategyContent.Add(tem);  //该策略 
                }


            }

            ViewBag.TotalNum = TotalNum;//该练习题的小题的总数
            ViewBag.TestPaperDetail = tempStrategyContent;

            return View();
        }

        //练习集统计页面，查看学生完成情况
        public ActionResult PraStatistics(int CourseId)
        {
            ViewBag.courseId = CourseId;
            ViewBag.teaId = frontCurrentTea.GetUserID();
            return View();
        }
    }
}
